<script lang="ts">
  import { AppBar } from "@skeletonlabs/skeleton-svelte";
  import { getCurrentWindow } from "@tauri-apps/api/window";
  import { Maximize, Minus, X } from "lucide-svelte";
  import { windowStore } from "./store.svelte";
  import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
  import { listen } from "@tauri-apps/api/event";
  import type { AllNotice } from "$lib/api/notice_type";

  let { children } = $props();

  function initTheme() {
    const curTheme = (() => {
      if (
        typeof localStorage !== "undefined" &&
        localStorage.getItem("theme")
      ) {
        return localStorage.getItem("theme");
      }
      return "cerberus";
    })();

    document.documentElement.setAttribute("data-theme", curTheme ?? "cerberus");
  }

  function init() {
    initTheme();
    const curWin = getCurrentWebviewWindow();
    curWin.setAlwaysOnTop(false);
  }

  init();

  $effect(() => {
    const unListen = listen<AllNotice>("notice", (ev) => {
      const payload = ev.payload;
      if (payload.ClientNotice != undefined) {
        if (payload.ClientNotice.ThemeChangeNotice != undefined) {
          initTheme();
        }
      }
    });
    return () => {
      unListen.then((fn) => fn());
    };
  });
</script>

<div>
  <AppBar
    padding="p-0"
    trailPadding="p-[10px]"
    trailSpaceX="gap-0"
    background="bg-surface-300-700"
    classes="h-[50px]"
  >
    {#snippet lead()}
      <div class="p-0 pl-[10px]">
        {#if windowStore.title != null}
          {@render windowStore.title()}
        {/if}
      </div>
    {/snippet}
    {#snippet trail()}
      <button
        type="button"
        class="btn btn-sm hover:preset-tonal p-2"
        onclick={() => getCurrentWindow().minimize()}
      >
        <Minus size={16} />
      </button>
      <button
        type="button"
        class="btn btn-sm hover:preset-tonal p-2"
        onclick={() => getCurrentWindow().toggleMaximize()}
      >
        <Maximize size={16} />
      </button>
      <button
        type="button"
        class="btn btn-sm hover:preset-tonal p-2"
        onclick={() => getCurrentWindow().close()}
      >
        <X size={16} />
      </button>
    {/snippet}
  </AppBar>
  <div class="h-[calc(100vh-50px)] overflow-hidden bg-surface-100-900">
    {@render children()}
  </div>
</div>
